﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Donal.Xms.Common;

namespace Donal.Xms.Web.temp.main
{
    public partial class confirm : Web.UI.UserPage
    {
        private string discount_remark = "";
        public decimal _amount = 0;
        private string goods_ids = "";
        Dictionary<int, int> dicGoodsIdQuantity = new Dictionary<int, int>();
        private string _temp = "";
        private DataSet dsGoods = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {
            Session[DTKeys.SESSION_ORDER_CONFIRM_INDEX] = 0;

            Session[DTKeys.SESSION_ORDER_CONFIRM] = "9840238B8E9C9D72A913B758997EECF6";//测试永远不过期

            if (Session[DTKeys.SESSION_ORDER_CONFIRM] != null)
            {
                try
                {
                    _temp = Session[DTKeys.SESSION_ORDER_CONFIRM].ToString();
                    _temp = DESEncrypt.Decrypt(_temp);
                    _temp = _temp.Split('_')[1];

                    string[] items = _temp.Split(',');

                    foreach (string item in items)
                    {
                        string[] id_auantity = item.Split('-');
                        if (!dicGoodsIdQuantity.ContainsKey(Utils.ObjToInt(id_auantity[0])))
                        {
                            goods_ids += id_auantity[0] + ",";
                            dicGoodsIdQuantity.Add(Utils.ObjToInt(id_auantity[0]), Utils.ObjToInt(id_auantity[1]));
                        }
                    }

                    goods_ids = goods_ids.Substring(0, goods_ids.Length - 1);
                }
                catch
                {
                    Response.Redirect(linkurl("index"));
                    return;
                }
            }
            else
            {
                Response.Redirect(linkurl("index"));
                return;
            }

            RptBind();
            BindAddress();
        }

        #region 数据绑定=================================

        private void RptBind()
        {
            try
            {
                dsGoods = new BLL.products_goods().GetListView(0, "id in(" + goods_ids + ")", "id");

                if (Utils.CheckDataSet(dsGoods))
                {
                    dsGoods.Tables[0].Columns.Add("quantity");
                    dsGoods.Tables[0].Columns.Add("index");
                    dsGoods.Tables[0].Columns.Add("amount");
                    dsGoods.Tables[0].Columns.Add("fields");
                    dsGoods.Tables[0].Columns.Add("discount_price");
                    dsGoods.Tables[0].Columns.Add("discount_remark");

                    int index = 1;
                    foreach (DataRow dr in dsGoods.Tables[0].Rows)
                    {
                        dr["discount_price"] = GetSpecPrice(Utils.ObjToInt(dr["id"]),
                            dr["title"].ToString(),
                            Utils.ObjToInt(dr["products_id"]),
                            dr["product_title"].ToString(),
                            Utils.ObjToInt(dr["category_id"]),
                            dr["category_title"].ToString(),
                            Utils.ObjToDecimal(dr["sell_price"], 0),
                            out discount_remark
                        );
                        dr["discount_remark"] = discount_remark;
                        dr["index"] = index++;
                        dr["fields"] = GetFields(Utils.ObjToInt(dr["id"]));

                        if (dicGoodsIdQuantity.ContainsKey(Utils.ObjToInt(dr["id"])))
                        {
                            dr["quantity"] = dicGoodsIdQuantity[Utils.ObjToInt(dr["id"], 1)];
                        }
                        else
                        {
                            dr["quantity"] = 1;
                        }

                        dr["amount"] = Math.Round(Utils.ObjToDecimal(dr["sell_price"], 0) * Utils.ObjToInt(dr["quantity"], 1), 2);

                        _amount += Utils.ObjToDecimal(dr["amount"], 0);
                    }
                }

                Session[DTKeys.SESSION_ORDER_SUBMIT] = dsGoods;
            }
            catch
            {
                Response.Redirect(linkurl("index"));
                return;
            }

            if (Utils.CheckDataSet(dsGoods))
            {
                // 获取该列的唯一值           
                var distinctValues = dsGoods.Tables[0].AsEnumerable()
                                .Select(row => Convert.ToString(row["products_id"]))
                                .Distinct()
                                .ToList();

                DataTable _tempDt = new DataTable();
                _tempDt.Columns.Add("id");

                for (int i = 0; i < distinctValues.Count; i++)
                {
                    DataRow dr = _tempDt.NewRow();
                    dr[0] = distinctValues[i];
                    _tempDt.Rows.Add(dr);
                }

                rptCategory.DataSource = _tempDt;
                rptCategory.DataBind();
            }

        }

        #endregion

        protected void rptCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater rep = e.Item.FindControl("rptList") as Repeater;

                HiddenField hidId = (HiddenField)e.Item.FindControl("hidId");

                int id = Convert.ToInt32(hidId.Value);

                DataView dv = dsGoods.Tables[0].DefaultView;
                // 应用筛选器
                dv.RowFilter = "products_id=" + id;
                // 应用排序规则（可选）
                dv.Sort = "add_time DESC";

                rep.DataSource = dv;
                rep.DataBind();
            }

        }

        private string GetFields(int goods_id)
        {
            List<Model.products_goods_filed> fileds = new BLL.products_goods().GetFields(goods_id);
            if (fileds == null || fileds.Count == 0)
            {
                return "---";
            }
            else
            {
                string fieldString = "";
                foreach (Model.products_goods_filed f in fileds)
                {
                    fieldString += f.field_title + "：" + f.field_value + "</br>";
                }
                return fieldString;
            }
        }

        #region 绑定地址

        private void BindAddress()
        {
            DataSet dsAddress = new BLL.user_addr_book().GetList("user_id=" + GetUserInfo().parent_id);

            if (Utils.CheckDataSet(dsAddress))
            {
                int index = 0;
                foreach (DataRow dr in dsAddress.Tables[0].Rows)
                {
                    if (dr["is_default"].ToString() == "1" && index == 0)
                    {
                        index++;
                    }
                    else
                    {
                        dr["is_default"] = 0;
                    }
                }
                if (index == 0)
                {
                    dsAddress.Tables[0].Rows[0]["is_default"] = 1;
                }

                rptAddress.DataSource = dsAddress;
                rptAddress.DataBind();

            }
        }

        #endregion

    }
}